package com.iclient.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.iclient.dao.model.Img;
import com.iclient.dao.model.MCookie;
import com.iclient.dao.service.ImgService;
import com.iclient.dao.service.MCookieService;
import com.plugins.http.LocalCookie;
import com.plugins.http.LoginTool;

@Controller
public class SinaLoginController {
	
	@Autowired
	private ImgService imgService;
	@Autowired
	private MCookieService mCookieService;
	
	@RequestMapping(value="/sina/login/index.html")
	public String index(){
		return "/sina/login";
	}
	
	@RequestMapping(value="/sina/login.json")
	@ResponseBody
	public Object dologin(){
		if(!check()){
			imgService.delete("msinalogin");
			Thread t = new Thread(new Runnable() {
				@Override
				public void run() {
					LoginTool.login();
				}
			});
			t.start();
			try{
				Thread.sleep(5000);
			}catch(Exception e){}
			return imgService.findImg("msinalogin");
		}
		return true;
	}
	
	@RequestMapping(value="/sina/login/submit.json")
	@ResponseBody
	public String dubmitImg(String code){
		Img img = imgService.findImg("msinalogin");
		img.setCode(code);
		imgService.update(img);
		return "success";
	}
	
	@RequestMapping(value="/sina/login/check.json")
	@ResponseBody
	public Boolean doCheck(){
		return check();
	}
	
	private Boolean check(){
		MCookie cookie = mCookieService.findByType("msinalogin");
		if(cookie.getValid() == true){
			Boolean flag = LocalCookie.isValid(cookie.getContent());
			if(!flag){
				cookie.setValid(flag);
				mCookieService.updateMCookie(cookie);
			}
			return flag;
		}
		return false;
	}
}
